import 'package:flutter/material.dart';
import 'package:flutter_bilibili/core/viewmodel/feed_index_view_model.dart';
import 'package:flutter_bilibili/ui/pages/home/recommend/home_video_item.dart';
import 'package:flutter_bilibili/ui/shared/app_theme.dart';
import 'package:flutter_bilibili/ui/shared/image_assets.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_swiper_null_safety_flutter3/flutter_swiper_null_safety_flutter3.dart';
import 'package:provider/provider.dart';

import '../../../../core/model/feed_index_model.dart';
import '../../../../core/service/request/home_request.dart';
import '../../../shared/platform_judge.dart';
import '../../../widgets/bilibili_classical_header.dart';

class HYHomeRecommendScreen extends StatefulWidget {
  const HYHomeRecommendScreen({Key? key}) : super(key: key);

  @override
  State<HYHomeRecommendScreen> createState() => _HYHomeRecommendScreenState();
}

class _HYHomeRecommendScreenState extends State<HYHomeRecommendScreen>
    with AutomaticKeepAliveClientMixin, SingleTickerProviderStateMixin {
  final List<Widget> _homeRecommendWidgets = [];
  late ScrollController _easyRefreshScrollController;
  late SwiperController _swiperController;
  late ScrollController _gridViewController;
  late EasyRefreshController _easyRefreshController;

  @override
  void initState() {
    _easyRefreshController = EasyRefreshController();
    _swiperController = SwiperController();
    _easyRefreshScrollController = ScrollController();
    _gridViewController = ScrollController();
    super.initState();
  }

  @override
  void dispose() {
    _easyRefreshController.dispose();
    _swiperController.dispose();
    _easyRefreshScrollController.dispose();
    _gridViewController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    ///拿到共享数据
    return Consumer<HYFeedIndexViewModel>(
      builder: (ctx, feedIndexVM, child) {
        if (feedIndexVM.feedIndexItemList.isEmpty) {
          ///未加载出数据时显示
          return Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Image.asset(
                  ImageAssets.holderLoadingPNG,
                  width: 150.r,
                  height: 150.r,
                ),
                10.verticalSpace,
                TextButton(
                    style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all(
                          HYAppTheme.norMainThemeColors),
                    ),
                    onPressed: () {
                      ///有网络时拉取数据
                      feedIndexVM.clearData();
                      setState(() {});
                    },
                    child: Text(
                      "刷新一下",
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: HYAppTheme.xxSmallFontSize),
                    ))
              ],
            ),
          );
        }

        ///还没有数据就初始化数据
        if (_homeRecommendWidgets.isEmpty) {
          if (feedIndexVM.feedIndexItemList.length == 10) {
            ///单纯的十条数据
            _homeRecommendWidgets.add(
                buildHomeRecommendVideoCards(feedIndexVM.feedIndexItemList));
          } else if (feedIndexVM.feedIndexItemList.length == 11) {
            ///有轮播图的是十一条数据
            _homeRecommendWidgets.addAll([
              ///前三条视频数据为轮播图数据
              buildHomeRecommendCarousel(
                  feedIndexVM.feedIndexItemList[0].bannerItems!),

              ///后面的数据用于card
              buildHomeRecommendVideoCards(
                  feedIndexVM.feedIndexItemList.sublist(1)),
            ]);
          } else {
            SmartDialog.showToast("啥也木有!");
          }
        }

        ///上拉刷新和下拉加载
        return EasyRefresh(
          controller: _easyRefreshController,
          scrollController: _easyRefreshScrollController,
          header: BilibiliClassicalHeader(
            enableHapticFeedback: false,
            float: true,
          ),
          footer: ClassicalFooter(
              enableHapticFeedback: false, loadedText: '加载中...'),
          onRefresh: () async {
            HYHomeRequest.getFeedIndexData(
                    feedIndexVM.fetchFeedIndexParamsWithSign())
                .then((value) {
              feedIndexVM.refreshVideosData(value.data.items);
              _homeRecommendWidgets.insert(
                  0, buildHYHomeRefreshItemOneVideo(value.data.items[10]));
              _homeRecommendWidgets.insert(0,
                  buildHomeRecommendVideoCards(value.data.items.sublist(1, 9)));
            });
            await Future.delayed(const Duration(seconds: 2), () {
              setState(() {});
            });

            ///刷新数据（下拉动作）
          },
          onLoad: () async {
            ///加载数据（上拉动作）
            HYHomeRequest.getFeedIndexData(
                    feedIndexVM.fetchFeedIndexParamsWithSign())
                .then((value) {
              feedIndexVM.loadMoreVideosData(value.data.items);
              _homeRecommendWidgets
                  .add(buildHYHomeRefreshItemOneVideo(value.data.items[10]));
              _homeRecommendWidgets.add(
                  buildHomeRecommendVideoCards(value.data.items.sublist(1, 9)));
              setState(() {});
            });
          },
          child: Padding(
            padding:
                const EdgeInsets.only(left: 6, right: 6, top: 4, bottom: 0).r,
            child: Column(
              children: _homeRecommendWidgets,
            ),
          ),
        );
      },
    );
  }

  ///轮播图
  Widget buildHomeRecommendCarousel(List<BannerItem> bannerItems) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(4.r),
      child: Container(
        margin: const EdgeInsets.only(bottom: 8).r,
        height: 200.h, //这里的轮播图组件必须包裹在有高度的控件或者设置比例
        child: Swiper(
          controller: _swiperController,
          scale: PlatformJudge.platformJudgeIsPhone() ? 1 : .7,
          viewportFraction: PlatformJudge.platformJudgeIsPhone() ? 1 : .7,
          itemBuilder: (ctx, index) {
            return Stack(
              children: [
                FadeInImage(
                  fit: BoxFit.cover,
                  placeholderFit: BoxFit.cover,
                  placeholder: AssetImage(ImageAssets.icUpperVideoDefaultPNG),
                  image: NetworkImage(bannerItems[index].staticBanner!.image!),
                ),
                Positioned(
                  child: Text(
                    bannerItems[index].staticBanner!.title!,
                    style: TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: HYAppTheme.xxSmallFontSize,
                    ),
                  ),
                  left: 10.r,
                  bottom: 10.r,
                )
              ],
            );
          },
          itemCount: bannerItems.length,
          indicatorLayout: PageIndicatorLayout.SCALE,
          autoplayDelay: 3000,
          pagination: SwiperPagination(
              alignment: Alignment.bottomRight,
              margin:
                  const EdgeInsets.only(left: 0, right: 8, bottom: 8, top: 0)
                      .r),
          fade: 1.0,
          autoplay: true,
          scrollDirection: Axis.horizontal,
        ),
      ),
    );
  }

  ///视频列表
  Widget buildHomeRecommendVideoCards(List<FeedIndexItem> items) {
    return GridView.builder(
      primary: false,
      controller: _gridViewController,
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: items.length,
      gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
        mainAxisExtent: 215.h,
        maxCrossAxisExtent:
            PlatformJudge.platformJudgeIsPhone() ? 180.w : 100.w,
      ),
      itemBuilder: (ctx, index) {
        // print(data[index].aid);
        return HYHomeVideoItem(video: items[index]);
        // return Container();
      },
    );
  }

  ///单视频
  Widget buildHYHomeRefreshItemOneVideo(FeedIndexItem video) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(4.r),
      child: Container(
        margin: const EdgeInsets.symmetric(vertical: 8).r,
        height: 215.h,
        width: double.infinity,
        child: FadeInImage(
          fit: BoxFit.fill,
          placeholderFit: BoxFit.fill,
          placeholder: AssetImage(ImageAssets.icUpperVideoDefaultPNG),
          image: NetworkImage(
            video.cover!,
          ),
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
